package com.cskaoyan.shopping.api;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.dto.AllItemServiceResponse;
import com.cskaoyan.shopping.constants.ShoppingRetCode;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @Description:
 * @since: 2022-11-01 20:22
 * @author: lazy
 */
@RestController
public class SearchApiImpl {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ItemMapper itemMapper;

    @GetMapping("/rpc/items")
    AllItemServiceResponse getAllProductItem() throws IOException {
        AllItemServiceResponse allItemServiceResponse = new AllItemServiceResponse();
        BulkRequest bulkRequest = new BulkRequest();

        //查询所有商品信息
        List<Item> items = itemMapper.selectAll();
        for (Item item : items) {
            String itemJson = JSON.toJSONString(item);
            IndexRequest indexRequest = new IndexRequest("tb_item");
            //用商品id作为文档的唯一标识
            indexRequest.id(item.getId().toString());
            indexRequest.source(itemJson, XContentType.JSON);
            //添加到批量请求中
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        allItemServiceResponse.setCallData(null);
        allItemServiceResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        allItemServiceResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());


        return allItemServiceResponse;
    }
}
